#include "dialogaddiagram.h"
#include "ui_dialogaddiagram.h"

#include "logic.h"

#include <QString>

DialogADDiagram::DialogADDiagram(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::DialogADDiagram)
{

    ui->setupUi(this);

    ui->cbLocation->addItems(logic::getLocations());
//    ui->cbLocation->addItem(QString(tr("Шпаковский район")));
//    ui->cbLocation->addItem(QString(tr("Ставрополь")));
//    ui->cbLocation->setCurrentIndex(0);

    ui->deDate->setDate(QDate::currentDate());
    ui->cbPeriod->addItem(tr("Месяц"));

    ui->cbPeriod->addItem(tr("Год"));
    ui->cbPeriod->setCurrentIndex(0);

    connect(ui->cbLocation, SIGNAL(activated(int)),
            ui->swStavShpa, SLOT(setCurrentIndex(int)));

    ui->cbStreet1->addItems(logic::getSreets());
    ui->cbStreet1->setCurrentIndex(-1);
    ui->cbStreet2->addItems(logic::getSreets()); // fix задваивание улиц в памяти!!!
    ui->cbStreet2->setVisible(false);
    ui->lbStreet2->setVisible(false);
    ui->cbStreet2->setCurrentIndex(-1);

    ui->cbRoad1->addItems(logic::getRoads());
    ui->cbRoad1->setCurrentIndex(-1);
    ui->cbRoad2->addItems(logic::getRoads());  // fix задваивание дорог в памяти!!!
    ui->cbRoad2->setVisible(false);
    ui->lbRoad2->setVisible(false);
    ui->cbRoad2->setCurrentIndex(-1);

    chart = new Chart(0);
    chart->resize(600,400);

}

DialogADDiagram::~DialogADDiagram()
{
    delete ui;
}

void DialogADDiagram::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void DialogADDiagram::on_chbCrossroadStav_clicked()
{
    if (ui->chbCrossroadStav->isChecked()) {
        ui->lbHouse->setVisible(false);
        ui->leHouse->setVisible(false);
        ui->lbCorps->setVisible(false);
        ui->leCorps->setVisible(false);
        ui->lbStreet2->setVisible(true);
        ui->cbStreet2->setVisible(true);;
    }
    else {
        ui->lbHouse->setVisible(true);
        ui->leHouse->setVisible(true);
        ui->lbCorps->setVisible(true);
        ui->leCorps->setVisible(true);
        ui->lbStreet2->setVisible(false);
        ui->cbStreet2->setVisible(false);
    }
}

void DialogADDiagram::on_chbCrossroadShpa_clicked()
{
    if (ui->chbCrossroadShpa->isChecked()) {
        ui->lbKm->setVisible(false);
        ui->dsbKm->setVisible(false);
        ui->lbRoad2->setVisible(true);
        ui->cbRoad2->setVisible(true);
    }
    else {
        ui->lbKm->setVisible(true);
        ui->dsbKm->setVisible(true);
        ui->lbRoad2->setVisible(false);
        ui->cbRoad2->setVisible(false);
    }
}

// check validity of input data
bool DialogADDiagram::checkFormData()
{
    // planned for the future use
    return true;
}

void DialogADDiagram::updateQueryOptions()
{
    queryOptions.clear();
    queryOptionsSQL.clear();

    if(ui->cbLocation->currentIndex() == 0) {
        //Stavropol
        queryOptionsSQL.prepend("FROM `transstav` WHERE ");
        if(ui->cbDistrict->currentIndex() != -1) {
            queryOptions << "`distrid`=\"" +ui->cbDistrict->currentText() +"\"";
        }
        if(ui->cbStreet1->currentIndex() != -1) {
            queryOptions << "`str1id`=\"" +ui->cbStreet1->currentText() +"\" ";
        }
        if(ui->chbCrossroadStav->isChecked()) {
            if(ui->cbStreet2->currentIndex() != -1) {
                queryOptions << "`str2id`=\"" +ui->cbStreet2->currentText() +"\"";
            }
            else {
                if(!ui->leHouse->text().isEmpty()) {
                    queryOptions << "`hnum`=\"" +ui->leHouse->text() +"\"";
                }
                if(!ui->leCorps->text().isEmpty()) {
                    queryOptions << "`corps`=\"" +ui->leCorps->text() +"\"";
                }
            }
        }
    }
    else {
        queryOptionsSQL.append("FROM `transshpa` WHERE ");
        if(ui->cbRoad1->currentIndex() != -1) {
            queryOptions << "`road1id`=\"" +ui->cbRoad1->currentText() +"\"";
        }
        if(ui->chbCrossroadShpa->isChecked()) {
            if(ui->cbRoad2->currentIndex() != -1) {
                queryOptions << "`road2id`\"" +ui->cbRoad2->currentText() +"\"";
            }
        }
        else {
            if(ui->dsbKm->value() != 0) {
                queryOptions << "`km`=\"" +QString::number(ui->dsbKm->value()) +"\"";
            }
        }
    }
    if(ui->cbDTPType->currentIndex() != -1) {
        queryOptions << "`typedtpid`=\"" +ui->cbDTPType->currentText() +"\"";
    }
    if(ui->cbTypeTr->currentIndex() != -1) {
        queryOptions << "`typetrid`=\"" +ui->cbTypeTr->currentText() +"\"";
    }
}

void DialogADDiagram::on_pbMakeDiagram_clicked()
{
    QSqlQuery query;
    updateQueryOptions();

    if (ui->cbPeriod->currentText() == "Месяц") {
        chart->clearDiagram(ui->deDate->date().daysInMonth());
        chart->_url = QUrl(qApp->applicationDirPath() + "/charts/month.html");

        query.prepare(QString("SELECT DAYOFMONTH(datedtp),SUM(numaffected), SUM(numdead) %1 %2 %3 %4 ")
                      .arg(queryOptionsSQL)
                      .arg("YEAR(datedtp)=" +QString::number(ui->deDate->date().year()))
                      .arg(" AND MONTH(datedtp)=" +QString::number(ui->deDate->date().month()))
                      .arg(" GROUP BY 1") );
        if(!query.exec()) {
            qCritical() << "SQL execute ERROR: " +query.lastError().text()
                    +"\nQueryText: " +query.lastQuery();
        }
        else {
            qDebug() << query.lastQuery();
            while(query.next()) {
                if(query.value(0).toInt() - 1 < chart->data1.size()) {
                    chart->data1[query.value(0).toInt() - 1] = query.value(1).toInt();
                    chart->data2[query.value(0).toInt() - 1] = query.value(2).toInt();
                }
            }
        }
    }
    else if (ui->cbPeriod->currentText() == "Год") {
        chart->clearDiagram(12);
        chart->_url = QUrl(qApp->applicationDirPath() +"/charts/year_ready.html");
        query.prepare("SELECT  MONTH(datedtp),SUM(numaffected), SUM(numdead) " +queryOptionsSQL
                      +" YEAR(datedtp)=" +QString::number(ui->deDate->date().year())
                      +" GROUP BY 1" );
        if(!query.exec()) {
            qCritical() << "SQL execute ERROR: " +query.lastError().text()
                    +"\nQueryText: " +query.lastQuery();
        }
        else {
            qDebug() << query.lastQuery();
            while(query.next()) {
                qDebug() << query.value(0).toInt() << " " << query.value(1).toInt();
                if(query.value(0).toInt() - 1 < chart->data1.size()) {
                    chart->data1[query.value(0).toInt() - 1] = query.value(1).toInt();
                    chart->data2[query.value(0).toInt() - 1] = query.value(2).toInt();
                }
            }
        }
    }

    chart->mark1 = QString("Пострадавших");
    chart->mark2 = QString("Погибших");

    chart->resize(680, 460);
    chart->showChart();
    //chart->setData(true);
    chart->setFocus();
}

void DialogADDiagram::on_pbExportToXmlFile_clicked()
{
    qDebug() << "oh, shit!";
}

